import {
  DeleteOutlined,
  ExportOutlined,
  ImportOutlined,
  PlusOutlined,
  SearchOutlined,
  SwapLeftOutlined,
} from '@ant-design/icons';

import { Button, Col, Form, Input, Modal, Popconfirm, Row, Table } from 'antd';
import type { ColumnsType, ColumnType } from 'antd/lib/table';
import { useState, useEffect } from 'react';
import type { EmgItem, TableListPagination } from '../../data';
import { emg } from '../../service';

import EmgStyle from './EmgStyle.less';

import EmgDescriptions from './Descriptions';
import EmgForm from './EditForm';

import React from 'react';

const columns: ColumnType<EmgItem>[] = [
  {
    title: '商品序号',
    dataIndex: 'gNo',
    width: '80',
    align: 'center',
  },
  {
    title: '商品料号',
    dataIndex: 'copGNo',
    width: '120',
    align: 'center',
  },
  {
    title: '商品编码',
    dataIndex: 'codeTs',
    width: '220',
    align: 'center',
  },
  {
    title: '商品名称',
    dataIndex: 'gName',
    width: '180',
    align: 'center',
  },
  {
    title: '规格型号',
    dataIndex: 'gModel',
    width: '300',
    align: 'center',
  },
  {
    title: '申报计量单位',
    dataIndex: 'unit',
    width: '150',
    align: 'center',
  },
  {
    title: '法定第一单位',
    dataIndex: 'unit1',
    width: '130',
    align: 'center',
  },
  {
    title: '法定第二单位',
    dataIndex: 'unit2',
    width: '130',
    align: 'center',
  },
  {
    title: '申报单价',
    dataIndex: 'decPrice',
    align: 'center',
  },
  {
    title: '辅料标记',
    dataIndex: 'adjmtrMarkcd',
    align: 'center',
  },
  {
    title: '修改标记',
    dataIndex: 'modifyMark',
    align: 'center',
  },
  {
    title: '单耗质疑标志',
    dataIndex: 'ucnsTqsnFlag',

    align: 'center',
  },
  {
    title: '磋商标志',
    dataIndex: 'csttnFlag',

    align: 'center',
  },
];

const EmgDisplay: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  /**
   * 查询加载属性
   */
  const [loading, setLoading] = useState<boolean>(false);
  /**
   * table数据源
   */
  const [emgDataSource, setEmgDataSource] = useState<EmgItem[]>([]);
  /**
   * table分页属性
   */
  const [pagination, setPagination] = useState<TableListPagination>({
    total: 0,
    current: 1,
    pageSize: 10,
  });
  /**
   * 明细是否显示
   */
  const [detailVisible, handleDetailVisible] = useState<boolean>(false);
  /**
   * 录入、编辑界面属性
   */
  const [editProps, handleEditProps] = useState<{
    visible: boolean;
    title: string;
    actionType: string;
    key?: string;
  }>({
    visible: false,
    title: '',
    actionType: '',
  });

  const [form] = Form.useForm();

  const emsFormRef = React.createRef();

  const onSelectChange = (selectedRowKeys: Key[], selectedRows: EmgItem[]) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const fetch = (params = {}) => {
    setLoading(true);
    emg(params).then((res) => {
      setEmgDataSource(res.data);
      const p = { total: res.total | 0, current: res.current, pageSize: res.pageSize };
      console.log(p);
      setPagination(p);
      pagination.total = res.total ? res.total : 0;
      setLoading(false);
    });
  };

  const onFinish = (values) => {
    fetch({ ...values, current: pagination.current, pageSize: pagination.pageSize });
  };

  const handleTableChange = (params) => {
    fetch({ ...params, ...form.getFieldsValue() });
  };

  useEffect(() => {
    fetch();
  }, []);

  const tableAction = [
    {
      title: '操作',
      width: 150,
      align: 'center',
      key: 'option',
      fixed: 'left',
      render: (text, record, _, action) => [
        <Button
          type="link"
          onClick={() => {
            handleDetailVisible(true);
          }}
        >
          明细
        </Button>,
        <Button
          type="link"
          onClick={() => {
            handleEditProps({
              visible: true,
              title: '编辑成品信息',
              actionType: 'edit',
              key: record.preNo,
            });
            console.log(text, record, _, action);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          title="确认删除该商品?"
          //onConfirm={confirm}
          //onCancel={cancel}
          okText="确定"
          cancelText="取消"
        >
          <Button type="link" danger>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <>
      <Form name="EmsEmgSearch" form={form} style={{ margin: '0 20px' }} onFinish={onFinish}>
        <Row gutter={20}>
          <Col span={8}>
            <Form.Item label="商品序号">
              <Form.Item name="gNo" noStyle>
                <Input name="gNo" />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="商品料号">
              <Form.Item name="copGNo" noStyle>
                <Input name="copGNo" />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="商品编码">
              <Form.Item name="codeTs" noStyle>
                <Input name="codeTs" />
              </Form.Item>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={24} style={{ textAlign: 'right' }}>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />} ghost>
              查询
            </Button>
            <Button
              style={{ marginLeft: '8px' }}
              icon={<SwapLeftOutlined />}
              onClick={() => {
                form.resetFields();
              }}
            >
              重置
            </Button>
            <Button
              style={{ marginLeft: '8px' }}
              icon={<PlusOutlined />}
              onClick={() => {
                handleEditProps({ visible: true, title: '录入成品信息', actionType: 'add' });
              }}
            >
              录入
            </Button>
            <Button key="d" style={{ marginLeft: '8px' }} icon={<DeleteOutlined />} danger>
              删除
            </Button>
            <Button style={{ marginLeft: '8px' }} icon={<ImportOutlined />}>
              导入
            </Button>
            <Button style={{ marginLeft: '8px' }} icon={<ExportOutlined />}>
              导出
            </Button>
          </Col>
        </Row>
      </Form>

      <Table
        className={EmgStyle.EmgTable}
        columns={[...tableAction, ...columns] as ColumnsType<EmgItem> | undefined}
        scroll={{ x: 1600 }}
        bordered
        loading={loading}
        dataSource={emgDataSource}
        style={{ margin: '20px' }}
        size="middle"
        rowSelection={rowSelection}
        rowKey="gNo"
        pagination={{
          defaultCurrent: 1,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total) => `总共 ${total} 条`,
          ...pagination,
        }}
        onChange={handleTableChange}
      />
      <Modal
        visible={detailVisible}
        width="1000px"
        onCancel={() => {
          handleDetailVisible(false);
        }}
        footer={[
          <Button key="back" type="primary" onClick={() => handleDetailVisible(false)}>
            返回
          </Button>,
        ]}
      >
        <EmgDescriptions />
      </Modal>
      <Modal
        key="editModal"
        title={editProps.title}
        visible={editProps.visible}
        width="1000px"
        destroyOnClose
        onCancel={() => {
          handleEditProps({ visible: false, title: '', actionType: '' });
        }}
        footer={[
          <Button
            type="primary"
            onClick={() => {
              emsFormRef.current.reset();
            }}
            ghost
          >
            重 置
          </Button>,
          <Button
            type="primary"
            onClick={() => {
              emsFormRef.current.validate().then(() => {
                emsFormRef.current.submit();
                handleEditProps({ visible: false, title: '', actionType: '' });
              });
            }}
          >
            保 存
          </Button>,
          <Button
            key="back"
            onClick={() => handleEditProps({ visible: false, title: '', actionType: '' })}
          >
            返 回
          </Button>,
        ]}
      >
        <EmgForm onRef={emsFormRef} actionType={editProps.actionType} preNo={editProps.key} />
      </Modal>
    </>
  );
};

export default EmgDisplay;
